package cn.com.connext.scrm.service;

import cn.com.connext.scrm.client.MemberClient;
import cn.com.connext.scrm.domain.master.SystemMessage;
import cn.com.connext.scrm.domain.master.SystemMessageUserLog;
import cn.com.connext.scrm.repository.master.SystemMessageRepository;
import cn.com.connext.scrm.repository.master.SystemMessageUserLogRepository;
import cn.com.connext.scrm.service.dto.SystemMessageUserLogDTO;
import cn.com.connext.scrm.service.mapper.SystemMessageMapper;
import cn.com.connext.scrm.service.mapper.SystemMessageUserLogMapper;
import cn.com.connext.scrm.web.rest.vm.UserIdVM;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: organization-service
 * @author: shawn
 * @create: 2019-06-04 10:44
 **/
@Service
@Transactional
public class SystemMessageUserLogService extends BaseService{
    private final Logger log = LoggerFactory.getLogger(SystemMessageUserLogService.class);

    @Autowired
    private SystemMessageUserLogRepository systemMessageUserLogRepository;

    @Autowired
    private SystemMessageUserLogMapper systemMessageUserLogMapper;

    @Autowired
    private SystemMessageRepository systemMessageRepository;

    @Autowired
    private SystemMessageMapper systemMessageMapper;

    @Autowired
    private MemberClient memberClient;

    protected SystemMessageUserLogService(SystemMessageUserLogRepository repository) {
        super(repository);
        this.systemMessageUserLogRepository = repository;
    }

    public Page<SystemMessageUserLogDTO> findAllByUserId(UserIdVM vm) {
        Page<SystemMessageUserLog> page = systemMessageUserLogRepository.findAll(new Specification<SystemMessageUserLog>() {
            @Override
            public Predicate toPredicate(Root<SystemMessageUserLog> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                Predicate p1 = cb.equal(root.get("userId"), vm.getUserId());
                list.add(p1);
                Predicate p2 = cb.equal(root.get("isSend"), true);
                list.add(p2);
                Predicate[] pre = new Predicate[list.size()];
                return query.where(list.toArray(pre)).getRestriction();
            }
        }, new PageRequest(vm.getPage() - 1, vm.getPageSize(), Sort.Direction.DESC, "createTime"));
        Page<SystemMessageUserLogDTO> dtos = page.map(paper -> systemMessageUserLogMapper.toDto(paper));
        for (SystemMessageUserLogDTO dto : dtos){
            String messageId = dto.getMessageId();
            SystemMessage message = systemMessageRepository.findOne(messageId);
            if (message != null){
                dto.setSystemMessageDTO(systemMessageMapper.toDto(message));
            }
        }
        return dtos;
    }


    @Async
    public void saveLog(String id, String userId, Boolean show) {
        log.info("进入异步存储私信,入参为:{}", id, userId, show);
        if (userId.contains(",")){
            String[] userIds = userId.split(",");
            systemMessageUserLogRepository.saveLogInUserId(id, show, userIds);
        }
        systemMessageUserLogRepository.saveByUserId(id, show, userId);
        log.info("异步存储结束");
    }


    @Async
    public void saveAllLog(String id, Boolean show) {
        log.info("进入异步存储私信,入参为:{}", id, show);
        systemMessageUserLogRepository.deleteById(id);
        systemMessageUserLogRepository.saveAllLog(id, show);
        log.info("异步存储广播结束");
    }

    @Async
    public void send(String id) {
        List<SystemMessageUserLog> logList = systemMessageUserLogRepository.findByMessageId(id);
        List<SystemMessageUserLog> result = new ArrayList<>();
        for (SystemMessageUserLog log : logList){
            log.setSend(true);
            log.setUpdateTime(ZonedDateTime.now());
            result.add(log);
        }
        systemMessageUserLogRepository.save(result);

    }

    public SystemMessageUserLog findById(String id) {
        SystemMessageUserLog log = systemMessageUserLogRepository.findOne(id);
        return log;
    }

    public void isRead(SystemMessageUserLog log) {
        log.setRead(true);
        log.setUpdateTime(ZonedDateTime.now());
        systemMessageUserLogRepository.save(log);
    }

    public Integer findCountByUserId(String userId) {
        Integer num = systemMessageUserLogRepository.findCountByUserId(userId);
        return num;
    }

    public void deleteByMessageId(String id) {
        systemMessageUserLogRepository.deleteById(id);
    }
}
